package 多线程.消费者生产者;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProuducerAndConsumer {
    public static void main(String[] args) {
        Data d = new Data();
        new Thread(()->{
            d.produce();
        },"生产者").start();
        new Thread(()->{
            d.consume();
        },"消费者1").start();
        new Thread(()->{
            d.consume();
        },"消费者2").start();
    }
}

class Data{
        private static int num = 0;
        Lock lock = new ReentrantLock();
        Condition con = lock.newCondition();
    public void produce(){
        while(true){
            lock.lock();
            try{

                while (num==20){
                    con.await();
                }
                num++;
                System.out.println(Thread.currentThread().getName()+"生产"+"目前有"+num+"件物品");
                con.signal();
                Thread.sleep(100);


            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }

    public void consume(){
        while(true){
            lock.lock();
            try{

                while (num==0){
                    con.await();
                }

                num--;
                System.out.println(Thread.currentThread().getName()+"消费"+"目前有"+num+"件物品");
                con.signal();
                Thread.sleep(100);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }

}


